package com.liting.uitest.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.liting.uitest.entity.InteractRecord;
import com.liting.uitest.mapper.InteractRecordMapper;
import com.liting.uitest.model.ReactionResult;
import com.liting.uitest.service.InteractRecordService;
import com.liting.uitest.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class InteractRecordServiceImpl extends ServiceImpl<InteractRecordMapper, InteractRecord> implements InteractRecordService {
    @Autowired
    private InteractRecordMapper recordMapper;

    @Override
    public InteractRecord uploadRectFile(MultipartFile[] files, short type) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String folderName = df.format(new Date());

        InteractRecord interactRecord = new InteractRecord();
        if (type == InteractRecord.InteractType_GOMS) {
            interactRecord.setType(new Short(InteractRecord.InteractType_GOMS));
        } else {
            interactRecord.setType(new Short(InteractRecord.InteractType_Fanying));
        }

        List<String> imgUrl = new ArrayList<>();


        for (MultipartFile multipartFile : files) {
            //String originalFilename = multipartFile.getOriginalFilename();
            String filename = multipartFile.getOriginalFilename();
            String ext1 = filename.substring(filename.lastIndexOf(".") + 1);

            if (ext1.equals("txt")) {
                String txtUrl = FileUtil.getUploadDate(multipartFile, folderName);
                parseTxt(txtUrl, interactRecord, type);
                interactRecord.setTxtUrl(txtUrl);
            } else {
                String uploadPath = FileUtil.getUploadDate(multipartFile, folderName);
                imgUrl.add(uploadPath);
            }
        }

        interactRecord.setImgUrl(JSON.toJSONString(imgUrl));

        Date nowTime = new Date();
        interactRecord.setCreateTime(nowTime);

        String name = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(nowTime);
        if (type == InteractRecord.InteractType_GOMS) {
            name = name + " GOMS评价";
        } else {
            name = name + " 反应时评价";
        }

        interactRecord.setName(name);

        baseMapper.insert(interactRecord);


        return interactRecord;

    }

    @Override
    public InteractRecord getLastResult(String beginTime) throws Exception {
        return null;
    }

    @Override
    public IPage<InteractRecord> getList(Integer pageNum, Integer pageSize, String type, String beginTime) {
//        QueryWrapper<InteractRecord> queryWrapper=new QueryWrapper<>();
//        queryWrapper.orderByDesc("create_time");
        Date queryDate = null;

        if (beginTime != null) {
            if (!(beginTime.trim().equals(""))) {
                try {
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    queryDate = df.parse(beginTime);
                    //queryWrapper.gt("create_time",queryDate);
                } catch (Exception ex) {
                    log.error("getFileList format date error", ex);
                }
            }
        }
//        queryWrapper.eq("type",type);
        IPage<InteractRecord> page = new Page<>(pageNum, pageSize);

        List<InteractRecord> list = recordMapper.selectListPage(page, type, queryDate);
        page.setRecords(list);

        return page;
    }

    @Override
    public InteractRecord getRecordInfo(Long id) {
        InteractRecord record = baseMapper.selectById(id);
        return record;
    }

    private void parseTxt(String txtUrl, InteractRecord interactRecord, short type) throws Exception {
        StringBuilder sb = new StringBuilder();

        // 使用ANSI编码方式读取文件
        FileInputStream fileInputStream = new FileInputStream(FileUtil.getFilePath(txtUrl));
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "gb2312");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);


        Stream<String> lines = bufferedReader.lines();

        // 将Stream转换为List
        List<String> lineList = lines.collect(Collectors.toList());

        int lineCount = lineList.size();

        int upLine = 0;

        String gomsStr, reactStr;

        if (lineList.get(lineCount - 1) == null) {
            String tempStr = lineList.get(lineCount - 2);
            if (tempStr.contains("GOMS")) {
                gomsStr = tempStr;
                reactStr = lineList.get(lineCount - 3);
            } else {
                reactStr = tempStr;
                gomsStr = lineList.get(lineCount - 3);
            }

            upLine = lineCount - 5;
        } else {
            String tempStr = lineList.get(lineCount - 1);
            if (tempStr.contains("GOMS")) {
                gomsStr = tempStr;
                reactStr = lineList.get(lineCount - 2);
            } else {
                reactStr = tempStr;
                gomsStr = lineList.get(lineCount - 2);
            }
            upLine = lineCount - 4;
        }

        if (type == InteractRecord.InteractType_GOMS) {
            if (gomsStr != null) {
                String[] gomsArray = gomsStr.split("=");
                interactRecord.setResult(gomsArray[gomsArray.length - 1]);
            }
        }

        if (type == InteractRecord.InteractType_Fanying) {
            if (reactStr != null) {
                String[] gomsArray = reactStr.split("=");
                interactRecord.setResult(gomsArray[gomsArray.length - 1]);
            }
        }


        for (int i = 0; i <= upLine; i++) {
            sb.append(lineList.get(i));
            interactRecord.setProcessInfo(sb.toString());
        }
    }

}
